package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Stock;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author eneko_lana
 *
 */
/**
 * implementation of StockDAOInterface
 * @author VB
 *
 */
public class StockDAO implements StockDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public StockDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one Stock by Id
	 * @param id
	 * @return Stock
	 */
	 @Transactional(readOnly = true)
	public Stock selectById(int id) {
		 Stock Stock = (Stock) getSession().get(Stock.class, id);
	    return Stock;
	}

	/*
	 * retrieves all Stocks from db
	 * @return List of Stocks
	 */
	 @Transactional(readOnly = true)
	 public List<Stock> selectAll() {
	 
	    List<Stock> Stocks = getSession().createQuery("from stock").list();
	    return Stocks;
	}
	
	/*
	 * retrieves all Stocks from db
	 * @return List of Stocks
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Stock> Stocks = getSession().createQuery("from stock").list();
	    return Stocks.size();
	}

	/*
	 * inserts a new Stock in database
	 * retrieves generated id and sets to Stock instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Stock Stock) {
	    Integer id = (Integer) getSession().save(Stock);
	    Stock.setId(id);           
	}

	/*
	 * updates Stock
	 * @param Stock to update
	 */
	 @Transactional
	public void update(Stock Stock) {
		getSession().merge(Stock);
	}

	/*
	 * delete given Stock
	 * @param Stock to delete
	 */
	 @Transactional
	public void delete(Stock Stock) {
		getSession().delete(Stock);
	}

	 @Transactional
	public void saveOrUpdate(Stock Stock) {

		getSession().saveOrUpdate(Stock);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Stock Stock = (Stock) getSession().load(Stock.class,id);
		 getSession().delete(Stock);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Stock> search(String description) {
		   Query query = getSession().createQuery("from stock s where s.description like :description");
           query.setParameter("description", "%"+description+"%");
           
           List<Stock> descriptions = query.list();
		
           return descriptions;
	}

}
